import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:gt_flutter_admin/app/routes.dart';
import 'package:gt_flutter_admin/constant/bool_num.dart';
import 'package:gt_flutter_admin/enum/user_sex.dart';
import 'package:gt_flutter_admin/models/index.dart';
import 'package:gt_flutter_admin/models/page.dart' as gt_page;
import 'package:gt_flutter_admin/services/api_service.dart';
import 'package:gt_flutter_admin/utils/toast_utils.dart';

class UserUpdateController extends GetxController with StateMixin<File> {
  // 数据
  final Rx<gt_page.Page> rolePage = gt_page.Page().obs;
  final Rx<gt_page.Page> deptPage = gt_page.Page().obs;

  final RxBool isEdit = true.obs;

  // 选择控件
  final RxBool statusSwitch = true.obs;
  final RxString sexRadio = UserSex.FEMALE.value.obs;

  String? avatar;

  List<num> roleIds = [];
  final RxString roleSelectedValue = ''.obs;
  final RxList<String> roleOptions = <String>[].obs;
  final RxList<bool> roleStatus = <bool>[].obs;

  num deptId = 0;
  final RxString deptSelectedValue = ''.obs;
  final RxList<String> deptOptions = <String>[].obs;

  List<num> deptIds = [];
  final RxString dataAuthSelectedValue = ''.obs;
  final RxList<String> dataAuthOptions = <String>[].obs;
  final RxList<bool> dataAuthStatus = <bool>[].obs;

  // 文本控件
  final TextEditingController usernameText = TextEditingController();
  final TextEditingController passwordText = TextEditingController();
  final TextEditingController emailText = TextEditingController();
  final TextEditingController mobileText = TextEditingController();
  final TextEditingController descriptionText = TextEditingController();

  @override
  void onInit() async {
    super.onInit();

    User? user = Get.rootDelegate.arguments();
    if (user != null) {
      isEdit.value = false;

      usernameText.text = user.username;
      emailText.text = user.email!;
      mobileText.text = user.mobile;
      statusSwitch.value = BoolNum.getBool(user.status);
      avatar = user.avatar;
      descriptionText.text = user.description!;
      sexRadio.value = UserSex.values[int.parse(user.sex)].value;

      roleIds = List<num>.from(user.roleIds!);
      deptIds = List<num>.from(user.deptIds!);
      deptId = user.deptId!;
    }

    // 初始化角色列表
    rolePage.value = await listRole();
    if (rolePage.value.rows?.isNotEmpty ?? false) {
      for (int i = 0; i < rolePage.value.rows!.length; i++) {
        Role role = Role.fromJson(rolePage.value.rows![i]);
        roleOptions.add(role.roleName);

        if (roleIds.isNotEmpty && roleIds.contains(role.id)) {
          roleSelectedValue.value += '${role.roleName} ';
          roleStatus.add(true);
        } else {
          roleStatus.add(false);
        }
      }
    }

    // 初始化部门选择列表
    deptPage.value = await listDept(isLast: true);
    if (deptPage.value.rows?.isNotEmpty ?? false) {
      for (int i = 0; i < deptPage.value.rows!.length; i++) {
        Dept dept = Dept.fromJson(deptPage.value.rows![i]);
        deptOptions.add(dept.deptName);
        dataAuthOptions.add(dept.deptName);
        deptSelectedValue.value = dept.deptName;

        if (deptIds.isNotEmpty && deptIds.contains(dept.id)) {
          dataAuthSelectedValue.value += '${dept.deptName} ';
          dataAuthStatus.add(true);
        } else {
          dataAuthStatus.add(false);
        }
      }
    }

    change(null, status: RxStatus.success());
  }

  /// 选择角色
  void onSelectRole(int index) {
    roleStatus[index] = !roleStatus[index];

    // 获取选中的角色
    Role role = Role.fromJson(rolePage.value.rows![index]);

    if (roleStatus[index]) {
      roleIds.add(role.id);
      roleSelectedValue.value += '${role.roleName} ';
    } else {
      roleIds.remove(role.id);
      roleSelectedValue.value = roleSelectedValue.value.replaceFirst(
        '${role.roleName} ',
        '',
      );
    }

    change(null, status: RxStatus.success());
  }

  /// 选择部门
  void onSelectDept(int index) {
    Dept dept = Dept.fromJson(deptPage.value.rows![index]);

    deptId = dept.id;
    deptSelectedValue.value = '${dept.deptName} ';

    change(null, status: RxStatus.success());
  }

  /// 选择数据权限
  void onSelectDataAuth(int index) {
    dataAuthStatus[index] = !dataAuthStatus[index];

    Dept dept = Dept.fromJson(deptPage.value.rows![index]);

    if (dataAuthStatus[index]) {
      deptIds.add(dept.id);
      dataAuthSelectedValue.value += '${dept.deptName} ';
    } else {
      deptIds.remove(dept.id);
      dataAuthSelectedValue.value = dataAuthSelectedValue.value.replaceFirst(
        '${dept.deptName} ',
        '',
      );
    }

    change(null, status: RxStatus.success());
  }

  /// 提交表单
  void onSubmit() async {
    Map<String, dynamic> data = {
      'username': usernameText.text,
      'password': passwordText.text,
      'email': emailText.text,
      'mobile': mobileText.text,
      'status': BoolNum.getNum(statusSwitch.value),
      'sex': '${UserSex.getIndex(sexRadio.value)}',
      'avatar': avatar,
      'description': descriptionText.text,
      'roleIds': roleIds,
      'deptId': deptId,
      'deptIds': deptIds,
    };

    User? user = Get.rootDelegate.arguments();

    if (user == null) {
      await createUser(data);
      ToastUtils.success('新增成功');
    } else {
      data['id'] = user.id;
      await updateUser(data);
      ToastUtils.success('编辑成功');
    }

    Get.rootDelegate.offNamed(Routes.USER);
  }
}
